const express = require('express')

const mysql = require('../database/index')

const router = express.Router()


//获取用户信息
router.get('/userinfo',(req,resp)=>{
    // id从token中获取req.user.id  login.js中查询到的userinfo信息
    let sql = `select * form user where id = ${req.user.id}`
    mysql(sql,(err,res)=>{
        // 抛给next
        // if(err) return next(err) 
        if(err) throw err

        if(res.length!==1) return res.send({
            status:1,
            message:'用户不存在'
        })
        res.send({
            status:0,
            message:'获取用户信息成功',
            // 对象放在数组中
            data:res[0]
        })

    })

    resp.send('获取用户信息成功')
})


// 修改用户信息
router.post('/userinfo',(req,resp)=>{
    let{id,nickname,email} = req.body
    let sql  =`update user set nickname='${nickname}',email='${email}' where id=${id};`
    mysql(sql,(err,res)=>{
        if(err) throw err
        if(res.affectedRows!==1) return resp.send({
            status:1,
            message:'数据库操作失败'
        })
        resp.send({
            status:0,
            message:'修改用户信息成功'
        })
    })
})


//修改密码
router.post('/updatepwd',(resq,resp)=>{
    let{oldPwd,newPwd}=resq.body

    const utility =require('utility')

    oldPwd = utility.md5(oldPwd)
    newPwd = utility.md5(newPwd)

    let sql = `select * from user where id = ${resq.body.id} and password='${oldPwd}'`


    mysql(sql,(err,res)=>{
        if(err)  throw err
        if(res.length==0) return resp.send({status:1,message:'查不到账号或密码错误!'})

         let sql = `update user set password = '${newPwd}' where id = ${resq.body.id};`

         mysql(sql,(err,res)=>{
             if(err) throw err
            if(res.affectedRows!==1) return resp.send({
                status:1,
                message:'修改密码失败!'
            })             
             resp.send({
                 status:0,
                 message:'修改密码成功!'
             })
         })

    })
})


//修改用户头像
router.post('/update/avatar',(req,resp)=>{
    // console.log(req);
    console.log(req);
    let sql = `update user set user_pic = "${req.body.avatar}" where id = ${req.user.id}`
    console.log(sql);
    mysql(sql,(err,res)=>{
        if(err) throw err
        if(res.affectedRows!==1) return resp.send({
            status:1,
            message:'数据库修改用户头像失败!'
        })
        resp.send({
            status:0,
            message:'修改用户头像成功!'
        })
    })
})

module.exports = router